package com.Lemon.Zhkuhealth.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.Lemon.Zhkuhealth.common.pojo.entity.ReserveSetting;
import com.Lemon.Zhkuhealh.api.service.IReserveSettingService;
import com.Lemon.Zhkuhealth.provider.mapper.ReserveSettingMapper;

import java.io.InputStream;
import java.io.OutputStream;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.util.StreamUtils;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;


@DubboService
@RequiredArgsConstructor
@Slf4j
public class ReserveSettingServiceImpl implements IReserveSettingService {

    private final ReserveSettingMapper reserveSettingMapper;
    @Override
    public void save(List<ReserveSetting> reserveSettings) {
        if (reserveSettings != null && !reserveSettings.isEmpty()) {
            for (ReserveSetting reserveSetting : reserveSettings) {
                // 1. 判断当前日期是否已经有预约数了
                QueryWrapper<ReserveSetting> queryWrapper = new QueryWrapper<ReserveSetting>().eq("orderdate", reserveSetting.getOrderDate());
                Long orderDateCount = reserveSettingMapper.selectCount(queryWrapper);
                if (orderDateCount > 0) {
                    // 2. 如果有预约数了，就修改预约数
                    reserveSettingMapper.updateById(reserveSetting);
                } else {
                    // 3. 如果没有预约数，就添加预约数
                    reserveSettingMapper.insert(reserveSetting);
                }
            }
        }
    }

    private static String ensureCorrectDateFormat(String date) {
        String[] parts = date.split("-");
        if (parts[1].length() == 1) {
            parts[1] = "0" + parts[1];
        }
        return String.join("-", parts);
    }

    @Override
    public List<ReserveSetting> listReserveSettingByMonth(String date) {
        // 确保日期格式正确 2023-9-01 -> 2023-09-01
        date = ensureCorrectDateFormat(date);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth yearMonth = YearMonth.parse(date, formatter); // 2023-09

        // 1. 获取当前月的第一天  yyyy-MM-dd 2023-09-01
        String begin = yearMonth.atDay(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
        // 2. 获取当前月的最后一天 2023-09-30
        String end = yearMonth.atEndOfMonth().format(DateTimeFormatter.ISO_LOCAL_DATE);

        QueryWrapper<ReserveSetting> queryWrapper
                = new QueryWrapper<ReserveSetting>().between("orderdate", begin, end);
        List<ReserveSetting> orderDate = reserveSettingMapper.selectList(queryWrapper);
        return orderDate;
    }
    @Override
    public void editReservations(List<ReserveSetting> reserveSettings) {
        for (ReserveSetting setting : reserveSettings) {
            // 构建查询条件，根据 orderDate 查找现有记录
            QueryWrapper<ReserveSetting> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderdate", setting.getOrderDate());

            // 查询是否存在该日期的预约设置
            ReserveSetting existingSetting = reserveSettingMapper.selectOne(queryWrapper);

            if (existingSetting != null) {
                // 如果存在，则更新可预约人数
                existingSetting.setNumber(setting.getNumber());
                reserveSettingMapper.updateById(existingSetting);
            } else {
                // 如果不存在，则插入新记录
                // 新增时，已预约人数通常初始化为0
                setting.setReservations(0);
                reserveSettingMapper.insert(setting);
            }
        }
    }
    /**
     * 下载预约设置Excel模板文件
     * 模板文件路径: static/attached/ordersetting_template.xlsx
     *
     * @param response HttpServletResponse 用于写入文件流
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 获取classpath下的模板文件资源
            // 假设模板文件在 src/main/resources/static/attached/ordersetting_template.xlsx
            Resource resource = new ClassPathResource("static/attached/ordersetting_template.xlsx");

            // 检查文件是否存在
            if (!resource.exists()) {
                log.error("预约设置模板文件不存在: {}", "static/attached/ordersetting_template.xlsx");
                response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404 Not Found
                response.setContentType(MediaType.TEXT_PLAIN_VALUE);
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("预约设置模板文件不存在。请联系管理员。");
                return;
            }

            // 设置响应头，告诉浏览器这是一个文件下载
            String fileName = "ordersetting_template.xlsx";
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

            // 将文件内容写入响应流
            try (InputStream is = resource.getInputStream();
                 OutputStream os = response.getOutputStream()) {
                // 使用 StreamUtils.copy 复制流
                StreamUtils.copy(is, os);
                os.flush();
            }

        } catch (Exception e) {
            log.error("下载预约设置模板失败: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500 Internal Server Error
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setCharacterEncoding("UTF-8");
            try {
                response.getWriter().write("下载模板失败，请稍后再试。错误信息：" + e.getMessage());
            } catch (Exception ex) {
                log.error("写入错误信息到响应失败", ex);
            }
        }
    }
    /**
     * 批量更新或保存预约设置
     * 根据ReserveSetting对象的id判断是更新还是新增。
     * 如果id不为空，则更新现有记录；如果id为空，则插入新记录。
     *
     * @param reserveSettings 包含预约设置数据的ReserveSetting对象列表
     */
    @Override
    public void updateOrSaveBatch(List<ReserveSetting> reserveSettings) {
        if (reserveSettings == null || reserveSettings.isEmpty()) {
            return;
        }

        for (ReserveSetting setting : reserveSettings) {
            // Convert String date to java.time.LocalDate if your entity uses Date and it's sent as String from frontend.
            // However, the frontend is sending 'YYYY-MM-DD', and if the controller's @RequestBody
            // correctly maps it to java.time.LocalDate or java.time.LocalDate, this step might not be needed here.
            // Assuming orderDate in ReserveSetting is already java.time.LocalDate or LocalDate by this point.

            if (setting.getId() != null) {
                // If ID exists, update the existing record
                reserveSettingMapper.update(setting, new UpdateWrapper<ReserveSetting>().eq("id", setting.getId()));
            } else {
                // If ID is null, insert a new record
                // Optionally set creation time or other default values if needed
                reserveSettingMapper.insert(setting); // Assuming an insert method in your mapper
            }
        }
    }
}
